<template>
  <view class="login-container">
    <!-- 顶部logo区域 -->
    <view class="logo-section">
      <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
      <text class="app-name">我的应用</text>
      <text class="app-desc">手机号快速登录</text>
    </view>

    <!-- 登录表单 -->
    <view class="form-section">
      <view class="input-group">
        <view class="input-item">
          <uni-icons type="phone" size="20" color="#999"></uni-icons>
          <input 
            class="input-field" 
            type="number" 
            placeholder="请输入手机号"
            v-model="loginForm.phone"
            maxlength="11"
          />
        </view>
        
        <view class="input-item">
          <uni-icons type="chatboxes" size="20" color="#999"></uni-icons>
          <input 
            class="input-field" 
            type="number" 
            placeholder="请输入验证码"
            v-model="loginForm.code"
            maxlength="6"
          />
          <button 
            class="code-btn" 
            :class="{ 'code-btn-disabled': !canGetCode || countdown > 0 }"
            :disabled="!canGetCode || countdown > 0"
            @click="getVerifyCode"
          >
            {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
          </button>
        </view>
      </view>

      <!-- 登录按钮 -->
      <button 
        class="login-btn" 
        :class="{ 'login-btn-active': canLogin }"
        :disabled="!canLogin"
        @click="handleLogin"
      >
        {{ loading ? '登录中...' : '登录' }}
      </button>

      <!-- 用户协议 -->
      <view class="agreement-section">
        <view class="agreement-item" @click="toggleAgreement">
          <uni-icons 
            :type="agreed ? 'checkbox-filled' : 'circle'" 
            size="16" 
            :color="agreed ? '#667eea' : '#999'"
          ></uni-icons>
          <text class="agreement-text">
            我已阅读并同意
            <text class="agreement-link" @click.stop="showUserAgreement">《用户协议》</text>
            和
            <text class="agreement-link" @click.stop="showPrivacyPolicy">《隐私政策》</text>
          </text>
        </view>
      </view>
    </view>

    <!-- 第三方登录 -->
   <!-- <view class="third-party-section">
      <view class="divider">
        <text class="divider-text">其他登录方式</text>
      </view>
      
      <view class="third-party-buttons">
        <view class="third-party-btn" @click="handleWechatLogin">
          <uni-icons type="weixin" size="24" color="#07C160"></uni-icons>
          <text class="third-party-text">微信</text>
        </view>
        
        <view class="third-party-btn" @click="handleQQLogin">
          <uni-icons type="qq" size="24" color="#12B7F5"></uni-icons>
          <text class="third-party-text">QQ</text>
        </view>
      </view>
    </view> -->
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { authApi } from '@/api/login.js'
import { userApi } from '@/api/user.js'

// 响应式数据
const loginForm = ref({
  phone: '',
  code: ''
})

const loading = ref(false)
const countdown = ref(0)
const agreed = ref(false)
let timer = null

// 计算属性
const canGetCode = computed(() => {
  return /^1[3-9]\d{9}$/.test(loginForm.value.phone)
})

const canLogin = computed(() => {
  return canGetCode.value && 
         loginForm.value.code.length === 6 && 
         agreed.value
})

// 方法
const toggleAgreement = () => {
  agreed.value = !agreed.value
}

const showUserAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement/user-agreement'
  })
}

const showPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages/agreement/privacy-policy'
  })
}

const getVerifyCode = async () => {
  // 1. 防止重复点击
  if (!canGetCode.value || countdown.value > 0) return
  
  // 2. 直接使用 loginForm.value.phone 获取手机号
  const phoneNumber = loginForm.value.phone
  
  
  // 3. 基础前端校验
  if (!phoneNumber?.trim()) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  
  // 手机号格式校验（中国手机号）
  if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
    uni.showToast({
      title: '手机号格式不正确',
      icon: 'none'
    })
    return
  }

  try {
    // 4. 显示加载状态
    uni.showLoading({
      title: '发送中...',
      mask: true
    })
    
    // 5. 调用真实接口
    await authApi.sendSms({"phone":phoneNumber})
    
    // 6. 发送成功处理
    uni.hideLoading()
    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    })
    
    // 7. 开始倒计时
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        timer = null
      }
    }, 1000)
    
  } catch (error) {
    // 8. 错误处理
    uni.hideLoading()
    uni.showToast({
      title: error.message || '发送失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer)
})

const handleLogin = async () => {
  if (!canLogin.value) return
  
  if (!agreed.value) {
    uni.showToast({
      title: '请先同意用户协议',
      icon: 'none'
    })
    return
  }
  
  loading.value = true
  
  try {
    const res = await authApi.loginByPhone({...loginForm.value})
        
        // ✅ 1. 确保使用正确的数据结构
        if (res.code !== 200) throw new Error(res.msg || '登录失败')
        
        // ✅ 2. 保存token (使用正确的路径)
        uni.setStorageSync('token', res.data.access_token) // 注意是res.data
    
        // ✅ 3. 获取用户信息 (使用新变量名)
        const userRes = await userApi.getInfo() 
        if (userRes.code !== 200) throw new Error('获取用户信息失败')
        
        
        // 4. 整理并保存用户信息（包含所有必要字段）
		    const fullUserInfo = {
		      // 用户基本信息
		      userId: userRes.user.userId,
		      userName: userRes.user.userName,
		      nickName: userRes.user.nickName,
		      phonenumber: userRes.user.phonenumber,
		      avatar: userRes.user.avatar,
		      sex: userRes.user.sex,
		      email: userRes.user.email,
		      
		      // 登录状态
		      loginTime: Date.now(),
		      loginIp: userRes.user.loginIp,
		      loginDate: userRes.user.loginDate,
		      
		      // 权限信息
		      roles: userRes.user.roles,       // 角色详情
		      roleKeys: userRes.roles,         // 角色 key 数组（如 ["common_user"]）
		      permissions: userRes.permissions,
		      
		      // 安全信息
		      isDefaultModifyPwd: userRes.isDefaultModifyPwd,
		      isPasswordExpired: userRes.isPasswordExpired,
		      pwdUpdateDate: userRes.user.pwdUpdateDate,
		      
		      // token
		      access_token: res.data.access_token,
		    };
        uni.setStorageSync('userInfo', fullUserInfo)
	
    
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })
    
    // 跳转到主页
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    }, 1500)
    
  } catch (error) {
    uni.showToast({
      title: error.message || '登录失败',
      icon: 'error'
    })
	console.log("error："+error.message)
  } finally {
    loading.value = false
  }
}

const handleWechatLogin = () => {
  if (!agreed.value) {
    uni.showToast({
      title: '请先同意用户协议',
      icon: 'none'
    })
    return
  }
  
  uni.showToast({
    title: '微信登录开发中',
    icon: 'none'
  })
}

const handleQQLogin = () => {
  if (!agreed.value) {
    uni.showToast({
      title: '请先同意用户协议',
      icon: 'none'
    })
    return
  }
  
  uni.showToast({
    title: 'QQ登录开发中',
    icon: 'none'
  })
}

// 生命周期
onMounted(() => {
  // 检查是否已登录
  const userInfo = uni.getStorageSync('userInfo')
  if (userInfo && userInfo.token) {
    // 检查登录是否过期（7天）
    const loginTime = userInfo.loginTime || 0
    const now = new Date().getTime()
    const expireTime = 7 * 24 * 60 * 60 * 1000 // 7天
    
    if (now - loginTime < expireTime) {
      uni.reLaunch({
        url: '/pages/tabbar/home/home'
      })
    } else {
      // 登录过期，清除本地数据
      uni.removeStorageSync('userInfo')
    }
  }
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0 40rpx;
  display: flex;
  flex-direction: column;
}

.logo-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 100rpx;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  border-radius: 24rpx;
  background: #fff;
  margin-bottom: 30rpx;
}

.app-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 10rpx;
}

.app-desc {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20rpx;
}

.form-section {
  flex: 2;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding-top: 80rpx;
}

.input-group {
  margin-bottom: 40rpx;
}

.input-item {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50rpx;
  padding: 0 30rpx;
  margin-bottom: 30rpx;
  height: 100rpx;
}

.input-field {
  flex: 1;
  margin-left: 20rpx;
  font-size: 32rpx;
  color: #333;
}

.code-btn {
  background: #667eea;
  color: #fff;
  border: none;
  border-radius: 30rpx;
  padding: 0 24rpx;
  height: 60rpx;
  font-size: 24rpx;
  white-space: nowrap;
}

.code-btn-disabled {
  background: #ccc;
  color: #999;
}

.login-btn {
  width: 100%;
  height: 100rpx;
  background: rgba(255, 255, 255, 0.3);
  border: 2rpx solid rgba(255, 255, 255, 0.5);
  border-radius: 50rpx;
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
}

.login-btn-active {
  background: rgba(255, 255, 255, 0.9);
  color: #667eea;
  border-color: transparent;
}

.agreement-section {
  margin-bottom: 40rpx;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
  padding: 0 10rpx;
}

.agreement-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 24rpx;
  line-height: 1.5;
  margin-left: 12rpx;
}

.agreement-link {
  color: #fff;
  text-decoration: underline;
}

.third-party-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  padding-bottom: 100rpx;
}

.divider {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 2rpx;
  background: rgba(255, 255, 255, 0.3);
}

.divider-text {
  color: rgba(255, 255, 255, 0.6);
  font-size: 24rpx;
  margin: 0 30rpx;
}

.third-party-buttons {
  display: flex;
  justify-content: center;
  gap: 80rpx;
}

.third-party-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
}

.third-party-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 24rpx;
  margin-top: 10rpx;
}
</style>
